import { Dialog } from "@/hoc/Diolog";
import { renderForm } from "@/hoc/renderForm";
import apiStore from "@/stores/apiStore";
import { isSuccessCode, useGloablLoading } from "@Tea/utils";
import { PropType, Ref, defineComponent, ref } from "vue";
import { ElMessage } from "element-plus"
import { EditPositionParam } from "@Tea/model";

export type AddPositionForm =  {
  positionCode: string,
  positionName: string,
}
export type PostionTitleType = "新增职位" | "编辑职位"
export const PositionDialog = defineComponent({
  props: {
    visible: {
      type: Object as PropType<Ref<boolean>>,
      required: true,
    },
    title: {
      type:  String as PropType<PostionTitleType>,
      required: true
    },
    ruleForm: {
      type: Object as PropType<AddPositionForm | EditPositionParam>,
      default: {
        positionCode: '',
        positionName: '',
      }
    },
    // 这里可以通过props 也可以 用 emiter
    handleSuccess: Function,
    handleFail: Function
  },
  setup(props, ctx) {
    const { Form, submitForm, resetForm} = renderForm({
      ruleForm: props.ruleForm,
      content: [
        [
          {
            span: 24,
            label: "职位编码",
            type: "text",
            feild: "positionCode"
          },
          {
            span: 24,
            label: "职位名称",
            type: "text",
            feild: "positionName"
          }
        ]
      ],
      rules: {
        positionCode: [
          {
            required: true, message: '请输入职位编码', trigger: 'blur',
          }
        ],
        positionName: [
          {
            required: true, message: '请输入职位名称', trigger: 'blur',
          }
        ],
      }
    });

    const { showLoading, closeLoading } = useGloablLoading()
    const { addPosition,editPosition } = apiStore().api

    // 检验成功时，loading 由 dialog 维护
    const onSuccess = async function () {
      showLoading()
      try {
        const { code, msg } = await (props.title === "新增职位" ? addPosition : editPosition)(props.ruleForm)
        closeLoading()
        if (isSuccessCode(code)) {
          ElMessage({
            message: msg,
            type:'success',
          })
          props.handleSuccess?.()
        }
      } catch (e) {
        closeLoading()
      }
    }

    return () => (
      Dialog({
        visible: props.visible,
        title: props.title,
        width: "600px",
        content: Form,
        onConfirm: () => submitForm(onSuccess),
        onClose: () => {
          resetForm()
        }
      })
    )
  },
})